package com.ruoyi.rpt.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * SQL执行器
 */
@Component
public class SqlExecutor {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    private static final List<String> UNSAFE_KEYWORDS = Arrays.asList(
            "INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "TRUNCATE", "RENAME",
            "GRANT", "REVOKE", "COMMIT", "ROLLBACK", "SAVEPOINT", "EXEC", "EXECUTE");

    /**
     * 执行查询SQL
     * 
     * @param sql SQL查询语句
     * @return 查询结果
     */
    public List<Map<String, Object>> executeQuery(String sql) {
        if (!isSafeSql(sql)) {
            throw new IllegalArgumentException("SQL语句包含不安全的操作");
        }
        return jdbcTemplate.queryForList(sql);
    }

    /**
     * 检查SQL是否安全（只允许SELECT语句）
     * 
     * @param sql SQL语句
     * @return 是否安全
     */
    public boolean isSafeSql(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return false;
        }
        
        String upperSql = sql.toUpperCase().trim();
        
        // 检查是否是SELECT语句
        if (!upperSql.startsWith("SELECT")) {
            return false;
        }
        
        // 检查是否包含不安全关键字
        for (String keyword : UNSAFE_KEYWORDS) {
            // 使用正则表达式检查整个单词
            String pattern = "\\b" + keyword + "\\b";
            if (Pattern.compile(pattern).matcher(upperSql).find()) {
                return false;
            }
        }
        
        return true;
    }
} 